<?php

namespace app\home\model\user;

use app\home\model\order\StoreOrder;
use basic\BaseModel;
use traits\ModelTrait;

/**
 * 用户模型
 * Class User
 * @package app\home\model\user
 */
class User extends BaseModel
{

    use ModelTrait;

    /**
     * 主键Id
     * @var string
     */
    protected $pk = "id";

    /**
     * 模型名称
     * @var string
     */
    protected $name = "user";

    /**
     * 数量
     * @return int
     */
    public static function getcount()
    {
        return self::where("wxapp_id", self::$wxapp_id)->count();
    }

    /**
     * 异步获取用户的信息
     * @param array $where
     * @return array
     */
    public static function getUserList(array $where)
    {
        $model = self::setWherePage(self::setWhere($where), $where, ['w.sex', 'w.province', 'w.city', 'u.status', 'u.is_promoter'], ['u.nickname', 'u.uid', 'u.phone']);
        $list = $model->alias('u')
            ->join('WechatUser w', 'u.uid=w.uid')
            ->where("u.wxapp_id", self::$wxapp_id)
            ->field('u.*,w.country,w.province,w.city,w.sex,w.unionid,w.openid,w.routine_openid,w.groupid,w.tagid_list,w.subscribe,w.subscribe_time')
            ->page((int)$where['page'], (int)$where['limit'])
            ->select()
            ->each(function ($item) {
                $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
                if ($item['last_time']) $item['last_time'] = date('Y-m-d H:i:s', $item['last_time']);//最近一次访问日期
                else $item['last_time'] = '无访问';//最近一次访问日期
                if ($item['spread_uid']) {
                    $item['spread_uid_nickname'] = self::where('uid', $item['spread_uid'])->value('nickname') . '/' . $item['spread_uid'];
                } else {
                    $item['spread_uid_nickname'] = '无';
                }
                if ($item['openid'] != '' && $item['routine_openid'] != '') {
                    $item['user_type'] = '通用';
                } else if ($item['openid'] == '' && $item['routine_openid'] != '') {
                    $item['user_type'] = '小程序';
                } else if ($item['openid'] != '' && $item['routine_openid'] == '') {
                    $item['user_type'] = '公众号';
                } else if ($item['user_type'] == 'h5') {
                    $item['user_type'] = 'H5';
                } else $item['user_type'] = '其他';
                if ($item['sex'] == 1) {
                    $item['sex'] = '男';
                } else if ($item['sex'] == 2) {
                    $item['sex'] = '女';
                } else $item['sex'] = '保密';
                $item['vip_name'] = false;
            });//->toArray();
        // echo $model->getLastSql();exit();
        $count = self::setWherePage(self::setWhere($where), $where, ['w.sex', 'w.province', 'w.city', 'u.status', 'u.is_promoter'], ['u.nickname', 'u.uid'])->where('w.wxapp_id', self::$wxapp_id)->alias('u')->join('WechatUser w', 'u.uid=w.uid')->count();
        return ['count' => $count, 'data' => $list];
    }


    /**
     * 设置搜索条件
     * @param $where
     * @return User
     */
    public static function setWhere($where)
    {
        if ($where['order'] != '') {
            $model = self::order(self::setOrder($where['order']));
        } else {
            $model = self::order('u.uid desc');
        }
        if ($where['user_time_type'] == 'visitno' && $where['user_time'] != '') {
            list($startTime, $endTime) = explode(' - ', $where['user_time']);
            $endTime = strtotime($endTime) + 24 * 3600;
            $model = $model->where("u.last_time < " . strtotime($startTime) . " OR u.last_time > " . $endTime);
        }
        if ($where['user_time_type'] == 'visit' && $where['user_time'] != '') {
            list($startTime, $endTime) = explode(' - ', $where['user_time']);
            $model = $model->where('u.last_time', '>', strtotime($startTime));
            $model = $model->where('u.last_time', '<', strtotime($endTime) + 24 * 3600);
        }
        if ($where['user_time_type'] == 'add_time' && $where['user_time'] != '') {
            list($startTime, $endTime) = explode(' - ', $where['user_time']);
            $model = $model->where('u.add_time', '>', strtotime($startTime));
            $model = $model->where('u.add_time', '<', strtotime($endTime) + 24 * 3600);
        }
        if ($where['pay_count'] !== '') {
            if ($where['pay_count'] == '-1') $model = $model->where('pay_count', 0);
            else $model = $model->where('pay_count', '>', $where['pay_count']);
        }
        if ($where['country'] != '') {
            if ($where['country'] == 'domestic') $model = $model->where('w.country', '中国');
            else if ($where['country'] == 'abroad') $model = $model->where('w.country', '<>', '中国');
        }
        return $model;
    }

    /**
     * 获取用户某个时间段的消费信息
     * @param $where
     * @param string $status
     * @param string $keep
     * @return array|array[]|float|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function consume($where, $status = '', $keep = '')
    {
        $model = new self;
        $user_id = [];
        if (is_array($where)) {
            if ($where['is_promoter'] != '') $model = $model->where('is_promoter', $where['is_promoter']);
            if ($where['status'] != '') $model = $model->where('status', $where['status']);
            switch ($where['date']) {
                case null:
                case 'today':
                case 'week':
                case 'year':
                    if ($where['date'] == null) {
                        $where['date'] = 'month';
                    }
                    if ($keep) {
                        $model = $model->whereTime('add_time', $where['date'])->whereTime('last_time', $where['date']);
                    } else {
                        $model = $model->whereTime('add_time', $where['date']);
                    }
                    break;
                case 'quarter':
                    $quarter = self::getMonth('n');
                    $startTime = strtotime($quarter[0]);
                    $endTime = strtotime($quarter[1]);
                    if ($keep) {
                        $model = $model->where('add_time', '>', $startTime)->where('add_time', '<', $endTime)->where('last_time', '>', $startTime)->where('last_time', '<', $endTime);
                    } else {
                        $model = $model->where('add_time', '>', $startTime)->where('add_time', '<', $endTime);
                    }
                    break;
                default:
                    //自定义时间
                    if (strstr($where['date'], '-') !== FALSE) {
                        list($startTime, $endTime) = explode('-', $where['date']);
                        $model = $model->where('add_time', '>', strtotime($startTime))->where('add_time', '<', bcadd(strtotime($endTime), 86400, 0));
                    } else {
                        $model = $model->whereTime('add_time', 'month');
                    }
                    break;
            }
        } else {
            if (is_array($status)) {
                $model = $model->where('add_time', '>', $status[0])->where('add_time', '<', $status[1]);
            }
        }
        if ($keep === true) {
            return $model->count();
        }
        if ($status === 'default') {
            return $model->group('from_unixtime(add_time,\'%Y-%m-%d\')')->field('count(uid) num,from_unixtime(add_time,\'%Y-%m-%d\') add_time,uid')->select()->toArray();
        }
        if ($status === 'grouping') {
            return $model->group('user_type')->field('user_type')->select()->toArray();
        }
        $uid = $model->field('uid')->select()->toArray();
        foreach ($uid as $val) {
            $user_id[] = $val['uid'];
        }
        if (empty($user_id)) {
            $user_id = [0];
        }
        if ($status === 'xiaofei') {
            $list = UserBill::where('uid', 'in', $user_id)
                ->group('type')
                ->field('sum(number) as top_number,title')
                ->select()
                ->toArray();
            $series = [
                'name' => isset($list[0]['title']) ? $list[0]['title'] : '',
                'type' => 'pie',
                'radius' => ['40%', '50%'],
                'data' => []
            ];
            foreach ($list as $key => $val) {
                $series['data'][$key]['value'] = $val['top_number'];
                $series['data'][$key]['name'] = $val['title'];
            }
            return $series;
        } else if ($status === 'form') {
            $list = WechatUser::where('uid', 'in', $user_id)->group('city')->field('count(city) as top_city,city')->limit(0, 10)->select()->toArray();
            $count = self::getcount();
            $option = [
                'legend_date' => [],
                'series_date' => []
            ];
            foreach ($list as $key => $val) {
                $num = $count != 0 ? (bcdiv($val['top_city'], $count, 2)) * 100 : 0;
                $t = ['name' => $num . '%  ' . (empty($val['city']) ? '未知' : $val['city']), 'icon' => 'circle'];
                $option['legend_date'][$key] = $t;
                $option['series_date'][$key] = ['value' => $num, 'name' => $t['name']];
            }
            return $option;
        } else {
            $number = UserBill::where('uid', 'in', $user_id)->where('type', 'pay_product')->sum('number');
            return $number;
        }
    }

    /**
     * 获取 相对于上月或者其他的数据
     * @param $date
     * @param bool $status
     * @param string $field
     * @param string $t
     * @return array
     */
    public static function getPostNumber($date, $status = false, $field = 'A.add_time', $t = '消费')
    {
        $model = new self();
        if (!$status) $model = $model->alias('A');
        switch ($date) {
            case null:
            case 'today':
            case 'week':
            case 'year':
                if ($date == null) {
                    $date = 'last month';
                    $title = '相比上月用户' . $t . '增长';
                }
                if ($date == 'today') {
                    $date = 'yesterday';
                    $title = '相比昨天用户' . $t . '增长';
                }
                if ($date == 'week') {
                    $date = 'last week';
                    $title = '相比上周用户' . $t . '增长';
                }
                if ($date == 'year') {
                    $date = 'last year';
                    $title = '相比去年用户' . $t . '增长';
                }
                $model = $model->whereTime($field, $date);
                break;
            case 'quarter':
                $title = '相比上季度用户' . $t . '增长';
                list($startTime, $endTime) = User::getMonth('n', 1);
                $model = $model->where($field, '>', $startTime);
                $model = $model->where($field, '<', $endTime);
                break;
            default:
                list($startTime, $endTime) = explode('-', $date);
                $title = '相比' . $startTime . '-' . $endTime . '时间段用户' . $t . '增长';
                $Time = strtotime($endTime) - strtotime($startTime);
                $model = $model->where($field, '>', strtotime($startTime) + $Time);
                $model = $model->where($field, '<', strtotime($endTime) + $Time);
                break;
        }
        if ($status) {
            return [$model->count(), $title];
        }
        $number = $model->join('user_bill B', 'B.uid=A.uid')->where('B.type', 'pay_product')->where('B.pm', 0)->sum('B.number');
        return [$number, $title];
    }

    /*
     * 获取 用户某个时间段的钱数或者TOP20排行
     *
     * return Array  || number
     */
    public static function getUserSpend($date, $status = '')
    {
        $model = new self();
        $model = $model->alias('A');
        switch ($date) {
            case null:
            case 'today':
            case 'week':
            case 'year':
                if ($date == null) $date = 'month';
                $model = $model->whereTime('A.add_time', $date);
                break;
            case 'quarter':
                list($startTime, $endTime) = User::getMonth('n');
                $model = $model->where('A.add_time', '>', strtotime($startTime));
                $model = $model->where('A.add_time', '<', bcadd(strtotime($endTime), 86400, 0));
                break;
            default:
                list($startTime, $endTime) = explode('-', $date);
                $model = $model->where('A.add_time', '>', strtotime($startTime));
                $model = $model->where('A.add_time', '<', bcadd(strtotime($endTime), 86400, 0));
                break;
        }
        if ($status === true) {
            return $model->join('user_bill B', 'B.uid=A.uid')->where('B.type', 'pay_product')->where('B.pm', 0)->sum('B.number');
        }
        $list = $model->join('user_bill B', 'B.uid=A.uid')
            ->where('B.type', 'pay_product')
            ->where('A.wxapp_id', self::$wxapp_id)
            ->where('B.pm', 0)
            ->field('sum(B.number) as totel_number,A.nickname,A.avatar,A.now_money,A.uid,A.add_time')
            ->order('totel_number desc')
            ->limit(0, 20)
            ->select()
            ->toArray();
        if (!isset($list[0]['totel_number'])) {
            $list = [];
        }
        return $list;
    }

    /*
     * 获取用户
     * 积分排行
     * 会员余额排行榜
     * 分销商佣金总额排行榜
     * 购物笔数排行榜
     * 购物金额排行榜
     * 分销商佣金提现排行榜
     * 上月消费排行榜
     * $limit 查询多少条
     * return array
     */
    public static function getUserTop10List($limit = 10, $is_promoter = 0)
    {
        //积分排行
        $integral = self::where('status', 1)
            ->where('is_promoter', $is_promoter)
            ->order('integral desc')
            ->field('nickname,phone,integral,FROM_UNIXTIME(add_time,"%Y-%m-%d") as add_time')
            ->limit($limit)
            ->select();
        count($integral) && $integral = $integral->toArray();
        //会员余额排行榜
        $now_money = self::where('status', 1)
            ->where('is_promoter', $is_promoter)
            ->order('now_money desc')
            ->field('nickname,phone,now_money,FROM_UNIXTIME(add_time,"%Y-%m-%d") as add_time')
            ->limit($limit)
            ->select();
        count($now_money) && $now_money = $now_money->toArray();
        //购物笔数排行榜
        $orderPayCount = StoreOrder::getOrderPayCount($is_promoter);
        if ($orderPayCount) {
            $shopcount = self::alias('a')
                ->join('store_order r', 'r.uid=a.uid')
                ->where('r.paid', 1)
                ->where('a.is_promoter', $is_promoter)
                ->group('r.uid')
                ->field('a.nickname,a.phone,count(r.uid) as sum_count,FROM_UNIXTIME(a.add_time,"%Y-%m-%d") as add_time')
                ->order('sum_count desc')
                ->limit($limit)
                ->select();
        } else $shopcount = [];
        count($shopcount) && $shopcount = $shopcount->toArray();
        //购物金额排行榜
        if ($orderPayCount) {
            $order = self::alias('a')
                ->join('store_order r', 'r.uid=a.uid')
                ->where('r.paid', 1)
                ->where('a.is_promoter', $is_promoter)
                ->group('r.uid')
                ->field('a.nickname,a.phone,sum(r.pay_price) as sum_price,FROM_UNIXTIME(a.add_time,"%Y-%m-%d") as add_time,r.uid')
                ->order('sum_price desc')
                ->limit($limit)
                ->select();
        } else $order = [];
        count($order) && $order = $order->toArray();
        //上月消费排行
        $orderPayCount = StoreOrder::getOrderPayMonthCount($is_promoter);
        if ($orderPayCount) {
            $lastorder = self::alias('a')
                ->join('store_order r', 'r.uid=a.uid')
                ->where('r.paid', 1)
                ->where('a.is_promoter', $is_promoter)
//                ->whereTime('r.pay_time','last month')
                ->where('r.pay_time', 'between', [strtotime(date('Y-m', strtotime('-1 month'))), strtotime(date('Y-m'))])
                ->group('r.uid')
                ->field('a.nickname,a.phone,sum(r.pay_price) as sum_price,FROM_UNIXTIME(a.add_time,"%Y-%m-%d") as add_time,r.uid')
                ->order('sum_price desc')
                ->limit($limit)
                ->select();
        } else $lastorder = [];
        count($lastorder) && $lastorder = $lastorder->toArray();
        return compact('integral', 'now_money', 'shopcount', 'order', 'lastorder');
    }

    /**
     * 获取所有的用户
     * @return mixed
     */
    public static function allUser()
    {
        return self::alias("u")
            ->join("wechat_user w", "w.uid = u.uid")
            ->where("u.wxapp_id", self::$wxapp_id)
            ->field("u.uid, u.phone, w.nickname, w.headimgurl")
            ->select();
    }
}